import { addMsgByKeyAndInfoObject } from './messageManager';
import WebsocketHeartbeatJs from './websocketHeartbeat';
import store from '../store';
function getWsUrl() {
    const userId = sessionStorage.getItem("userId") || '';
    const wsUrl = process.env.VUE_APP_WS_URL;
     console.log({ wsUrl, userId });
    //你们测试的时候使用的是ws，线上使用的wss， 打包之前后面地址要记得更改 不要要localhost了
    return wsUrl + '?userId=' + userId;
}
/**
 * websocket 连接处理
 * @param self vue
 */
function webSocketOperation(self) {
    let websocketHeartbeatJs = new WebsocketHeartbeatJs({
        url: getWsUrl(),
    });
    websocketHeartbeatJs.onopen = function () {
        websocketHeartbeatJs.send('{"code":' + 0 + '}');
    };
    websocketHeartbeatJs.onmessage = function (event) {
        console.log({ event });
        let data = event.data;
        if (typeof data === 'string') {
            data = JSON.parse(data);
        }
        let content = '';
        let type = '';
        if (data && data.message) {
            content = data.message.content;
            type = data.message.type;
        }
        if (content && typeof content === 'string') {
            setTimeout(() => {
                addMsgByKeyAndInfoObject(type, JSON.parse(content));
            }, 500);
        }
    };

    websocketHeartbeatJs.onreconnect = function () {
        console.log('reconnecting...');
    };
    websocketHeartbeatJs.onerror = function () {
        console.log('websocketHeartbeatJs onerror');
    };
    store.dispatch('app/setWebsocket', websocketHeartbeatJs);
}
export default webSocketOperation;
